/**
 * Created by Administrator on 2016/9/20.
 */
function sleep(n){
    var start = new Date().getTime();
    while (true) if (new Date().getTime() - start > n) break;
}
$(function(){
    //versionlist();
    whoactive();
    check();

});
//刷新验证码
$("#get_code_img").click(function(){
    $(".imgyz").attr("src", "/accounts/verify/code?rand=" + Math.random());
    return false;
});
//$(".imgyz").attr("src", "/accounts/verify/code?rand=" + Math.random());
//服务请求
function ajaxstart(name,id,jindu){
   $.ajax({
        //提交数据的类型 POST GET
        type:"POST",
        //提交的网址
        url:"/service/controler/",
        //提交的数据
        data:JSON.stringify({"ser":name,"id":id}),
        //返回数据的格式
        datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".
        //在请求之前调用的函数
        beforeSend:function(){
        },
        //成功返回之后调用的函数
        success:function(data){
            var msg = JSON.parse(data);
            layer.msg(msg.msg, {icon: 6});
            layer.close(jindu);
        },
        //调用执行后调用的函数
        complete: function(){

        },
        //调用出错执行的函数
        error: function(){

        }
   });
}
//服务控制启动
function qidong(title,server){
    layer.open({
        type: 1, //page层
        area: ['500px', '300px'],
        title: title,
        shade: 0.6, //遮罩透明度
        moveType: 1, //拖拽风格，0是默认，1是传统拖动
        shift: 1, //0-6的动画形式，-1不开启
        content: '<div style="padding:50px;">即将启动服务:'+server+'</div>',
        btn: ['确定', '取消'],
            btn1: function(index, layero){
                layer.close(index);
                var jindu=layer.load(0, {shade: false});
                ajaxstart(server,1,jindu)
            },
            btn2: function(index, layero){
                layer.closeAll();
            },
            cancel: function(){
    //右上角关闭回调
            }
    });
}

//显示版本详情
function disinfo(ver,info){
    var d = $("#dinfo");
    d.css("display","block");
    d.css("left", event.clientX + 20);
    d.css("top", event.clientY);
    var title = ver+"版本详情";
    $("#dtitle").text(title);
    $("#dcontent").text(info);
}
function dinone() {
    $("#dinfo").css("display","none");
}
//获取version列表
function versionlist() {
    var versionhtml="";
    var vcrypt= "";
    $.get("/service/versionlist/", function(result){
        var list = JSON.parse(result);
        for (var ver in list.data){
            var i =Number(ver) +1;
            if(list.data[ver].vcrypt==true){
                vcrypt="加密";
            }else{
                vcrypt="未加密";
            }
            if(list.data[ver].cus==''){
                list.data[ver].cus ='无'
            }
            versionhtml +='<tr onmouseover="disinfo(\''+list.data[ver].vsion+'\',\''+list.data[ver].vinfo+'\')" onmouseout="dinone()"><td>'+i+'</td>'+
                          '<td>'+list.data[ver].vsion+'</td>'+
                          '<td>'+vcrypt+'</td>'+
                          '<td>'+list.data[ver].vdate+'</td>'+
                          '<td>'+list.data[ver].cus+'</td></tr>';}
        $("#versionlist").html(versionhtml);
    });
}
//版本提交后初始化版本表单
function getversion(){
    $.get("/service/newversion", function(result) {
        result = JSON.parse(result);
        var ver = $('#versionver');
        ver.val(result.vsion);
    });
    $('#versioninfo').val("版本描述不能为空");
    $('#versionserver').val("");
    $('#versionrobot').val("");
    var aa=$('#versioncrypt');
        aa.attr("checked", false);
        aa.val("0");
    check();
}
//构建版本
function versionadd(){
     var formData = new FormData($("#versionadd")[0]);
     $.ajax({
          url: '/service/addversion/' ,
          type: 'POST',
          data: formData,
          async: false,
          cache: false,
          contentType: false,
          processData: false,
          success: function (returndata){
              var result = JSON.parse(returndata);
              alert(returndata);
              versionlist();
              getversion();
          },
          error: function (returndata){
              alert(returndata);
          }
     });
}
//检查版本提交信息
function check(){
    var info = $('#versioninfo').val();
    var server = $('#versionserver').val();
    var robot = $('#versionrobot').val();
    if ( info == '版本描述不能为空'|| server =='' || robot==''){
        $("#versionsave").attr("disabled", true);
    }else{
        $("#versionsave").attr("disabled", false);
    }
}
$('#versioninfo').blur(function (){
    if (this.value=== ''){
        this.value = '版本描述不能为空';
    }
    check();
});
$('#versionserver').change(function (){
    check();
});
$('#versionrobot').change(function (){
    check();
});

$("#versioncrypt").click(function(){
    if($("#versioncrypt").is(':checked')){
        this.value="1";
    }else{
        this.value="0";
    }
});

//conf ul li点击事件
function conflievent(){
    $("#ulmemser").find("a").each(function () {
        $(this).click(function () {
            $("#ulserbutton").text($(this).html());
        });
    });
    $("#ulmemrbo").find("a").each(function () {
        $(this).click(function () {
            $("#ulrbobutton").text($(this).html());
        });
    });
    //rbolis = $("#ulmemrbo li");
    // for(var i=0;i<serlis.length;i++){
    //     console.log( console.log([i]);
    //     serlis[i].click(function () {
    //         $("#ulserbutton").text(serlis[i].innerHTML);
    //     });
    // }
    // for(var j=0;j<rbolis.length;j++){
    //
    //     rbolis[j].click(function () {
    //         $("#ulrbobutton").text(rbolis[j].innerHTML);
    //     });
    // }
}

function getmems(){
    $.get("/service/memlimit/", function(result) {
        result = JSON.parse(result);
        var serlis='';
        var rbolis='';
        for(var i=0;i<result['ser'].length;i++){
            serlis+='<li><a href="javascript:;">'+result["ser"][i]+'</a></li>';
        }
        for(var j=0;j<result['rbo'].length;j++) {
            rbolis+='<li><a href="javascript:;">'+result["rbo"][j]+'</a></li>';
        }
        $("#ulmemser").html(serlis);
        $("#ulmemrbo").html(rbolis);
        conflievent();
    });
}

function conf(title, service){
    $('#conflabel').text('当前配置信息如下');
    $('#conftext').text(title+"基础配置");
    $('#loadingDiv').css('display','block');
    $('#confqueding').css('display','inline-block');
    $('#confquxiao').css('display','inline-block');
    $('#popup').slideDown();
    var str='{"service":"'+service+'"}';
    var confhtml = '';
    var jdata = JSON.parse(str);
    $.get("/service/serviceconf/",jdata, function(result){
        result = JSON.parse(result);
        confhtml = '<table>' + '<tr><td>服务名称</td><td>'+result.customname+'</td><tr>'+
                   '<tr><td>ServerHTTP端口</td><td>'+result.serverhttpport+'</td></tr>'+
                   '<tr><td>ServerTCP端口</td><td>'+result.servertcpport+'</td></tr>'+
                   '<tr><td>RobotHTTP端口</td><td>'+result.robothttpport+'</td></tr>'+
                   '<tr><td>IP白名单</td><td>'+result.backendips+'</td></tr>'+
                   '<tr><td>Server内存上限</td><td>'+result.servermem+'</td></tr>'+
                   '<tr><td>Robot内存上限</td><td>'+result.robotmem+'</td></tr></table>';
        $('#conftable').html(confhtml);
        editconf(result.backendips);
        $('#confqueding').unbind();
        $('#confqueding').click(function () {
            confupdate(service,result.backendips,result.servermem,result.robotmem);
        });
    });
}
function editconf(backendip) {
    var ips = backendip.split(",");
    var lis = '';
    for(var i=0;i<ips.length;i++){
        lis +='<li value="0">'+ips[i]+'</li>';
    }
    var confedit='<div class="confips" id="confips"> <ul id="test" class="test">'+lis+'</ul> </div><div class="deljt"><span class="glyphicon glyphicon-chevron-right"></div><div class="delbutton"><button type="button" class="btn btn-info" onclick="ipdel()">从白名单中移除</button></div> <div class="confmem"><div class="memserver"><span>Server内存上限:</span></div>'+
        '<div class="btn-group server"><button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" id="ulserbutton">请选取内存大小<span class="caret"></span></button><ul class="dropdown-menu" id="ulmemser">  </ul></div>'+
        '<div class="memrobot"><span>Robot内存上限:</span></div>' +
            '<div class="btn-group server"><button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" id="ulrbobutton">请选取内存大小<span class="caret"></span></button><ul class="dropdown-menu" id="ulmemrbo"> <li><a href="#">Another action</a></li> </ul></div>'+
        '</div></div> <div class="ipaddcontent"> <div class="addjt"><span class="glyphicon glyphicon-chevron-up"></span></div><div id="IPDiv" class="IPDiv"></div> <div class="addbutton"> <button id="addip" type="button" class="btn btn-success" onclick="ipadd()">添加至白名单</button></div></div></div>';
    $('#confedit').html(confedit);
    createiptext();
    addtestevent();
    createipbox();
    getmems();
}
function confupdate(service,oldips,oldmems,oldmemr){
    var ips=[];
    $("#test").find("li").each(function () {
        ips.push($(this).html());
    });
    var backip = ips.toString();
    var memser = $("#ulserbutton").text();
    var memrbo = $("#ulrbobutton").text();
    if(memser=="请选取内存大小"){
        memser=oldmems;
    }
    if(memrbo=="请选取内存大小"){
        memrbo=oldmemr;
    }
    if(backip==oldips && memser==oldmems && memrbo==oldmemr){
        alert("没有任何更改");
    }else{
        var args ={
            "service":service,
            "backip":backip,
            "memser":memser,
            "memrbo":memrbo
        };
        $('#confqueding').unbind();
        $.ajax({
        type:"POST",
        url:"/service/confupdate/",
        data:JSON.stringify(args),
        datatype: "json",
        beforeSend:function(){
        },
        success:function(data){
            if(data == 1){
                alert("配置更新成功");
            }else{
                alert("配置更新失败");
            }
            $('#popup').fadeOut();
            $('#loadingDiv').css('display','none');
            $('#confqueding').css('display','none');
            $('#confquxiao').css('display','none');
            $('#conflabel').html("");
            $('#confinfo').html("");
            $('#conftable').html("");
            $('#confedit').html("");
        },
        complete: function(){

        },
        error: function(){

        }
   });
    }



}
$('#confquxiao').click(function (){
    //$('#popup').hide();
    $('#popup').fadeOut();
    $('#loadingDiv').css('display','none');
    $('#confqueding').css('display','none');
    $('#confquxiao').css('display','none');
    $('#confquxiao').html("取消");
    $('#confedit').html("");
    $('#conflabel').html("");
    $('#confinfo').html("");
    $('#conftable').html("");
});
//版本升级请求
function verupdate(ver,service) {
    var args = {
        "service" : service,
        "ver" : ver
    };
    $('#confqueding').unbind();
    $.ajax({
        type:"POST",
        url:"/service/versionupdate/",
        data:JSON.stringify(args),
        datatype: "json",
        beforeSend:function(){
        },
        success:function(data){
            if(data == 1){
                alert("升级成功");
                $("#"+service+" td:nth-child(5)").html(ver);
            }else{
                alert("升级失败");
            }
            $('#popup').fadeOut();
            $('#loadingDiv').css('display','none');
            $('#confqueding').css('display','none');
            $('#confquxiao').css('display','none');
            $('#confinfo').html("");
            $('#conftable ').html("");


        },
        complete: function(){

        },
        error: function(){

        }
   });
}
//版本信息获取
function verinfo(ver,service){
    $('#confqueding').unbind();
    $('#confqueding').click(function () {
        verupdate(ver,service);
    });
    $('#verupbutton').text(ver);
    var jdata = '{"ver":"'+ver+'"}';
    jdata = JSON.parse(jdata);
    $.get("/service/versioninfo/",jdata, function(result){
        result = JSON.parse(result);
        if(result.vcrypt==true){
            vcrypt="加密";
        }else{
            vcrypt="未加密";
        }
        confhtml = '<span>该版本详情如下：</span><br><table><tr><td>版本发布时间</td><td>'+result.vdate+'</td><tr>'+
                   '<tr><td>是否加密</td><td>'+vcrypt+'</td></tr>'+
                   '<tr><td>版本详情</td><td>'+result.vinfo+'</td></tr></table>';
        var table = $('#conftable');
        table.html(confhtml);
        
    });

}
function vergoback(ver,service){
    var args = {
        "service" : service,
        "ver" : ver
    };
    $('#confqueding').unbind();
    $.ajax({
        type:"POST",
        url:"/service/verback/",
        data:JSON.stringify(args),
        datatype: "json",
        beforeSend:function(){
        },
        success:function(data){
            if(data == 1){
                alert("版本回滚成功");
                $("#"+service+" td:nth-child(5)").html(ver);
            }else{
                alert("版本回滚失败");
            }
            $('#popup').fadeOut();
            $('#loadingDiv').css('display','none');
            $('#confqueding').css('display','none');
            $('#confquxiao').css('display','none');
            $('#confinfo').html("");
            $('#conftable ').html("");


        },
        complete: function(){

        },
        error: function(){

        }
   });
}

function verbkinfo(ver,service){
    $('#confqueding').unbind();
    $('#confqueding').click(function () {
        vergoback(ver,service);
    });
    $('#verupbutton').text(ver);
    var jdata = '{"ver":"'+ver+'","service":"'+service+'"}';
    jdata = JSON.parse(jdata);
    $.get("/service/versionbkinfo/",jdata, function(result){
        result = JSON.parse(result);
        if(result.vcrypt==true){
            vcrypt="加密";
        }else{
            vcrypt="未加密";
        }
        confhtml = '<span>该版本详情如下：</span><br><table><tr><td>版本发布时间</td><td>'+result.vdate+'</td><tr>'+
                   '<tr><td>是否加密</td><td>'+vcrypt+'</td></tr>'+
                   '<tr><td>版本详情</td><td>'+result.vinfo+'</td></tr>'+
                   '<tr><td>版本详情</td><td>'+result.history+'</td></tr></table>';
        var table = $('#conftable');
        table.html(confhtml);

    });

}
//版本升级

function verup(title, service){
    $('#conftext').text(title+"服务版本升级");
    $('#loadingDiv').css('display','block');
    $('#popup').slideDown();
    var args = {
        "service" : service
    };
    $.ajax({
        type:"POST",
        url:"/service/versionup/",
        data:JSON.stringify(args),
        datatype: "json",
        beforeSend:function(){
        },
        success:function(data){
            result = JSON.parse(data);
            if(result["vers"] != ""){
                $('#conflabel').text('可用版本如下，请选择:');
                $('#confqueding').css('display','inline-block');
                $('#confquxiao').css('display','inline-block');
                vershead = '<div class="btn-group"><button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" id="verupbutton">请选择版本<span class="caret"></span></button><ul class="dropdown-menu versionlist">'
                var verhtml = '';
                for (var ver in result["vers"]){
                    version = result["vers"][ver];
                    verhtml +='<li><a href="javascript:;" onclick="verinfo(\''+version+'\',\''+service+'\')">'+version+'</a></li>';
                }
                versend = '</ul></div>';
                vershtml = vershead+verhtml+versend;
                $('#confinfo').html(vershtml);
            }else{

                $('#conflabel').text('当前已是最新版本');
                $('#confquxiao').css('display','inline-block');
            }

        },
        complete: function(){

        },
        error: function(){

        }
   });
}

//版本回滚
function verback(title, service){
    $('#conftext').text(title+"服务版本回滚");
    $('#loadingDiv').css('display','block');
    $('#popup').slideDown();
    var args = {
        "service" : service
    };
    $.ajax({
        type:"POST",
        url:"/service/versionbk/",
        data:JSON.stringify(args),
        datatype: "json",
        beforeSend:function(){
        },
        success:function(data){
            result = JSON.parse(data);
            if(result["vers"] != ""){
                $('#conflabel').text('历史版本如下，请选择:');
                $('#confqueding').css('display','inline-block');
                $('#confquxiao').css('display','inline-block');
                vershead = '<div class="btn-group"><button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" id="verupbutton">请选择版本<span class="caret"></span></button><ul class="dropdown-menu">'
                var verhtml = '';
                for (var ver in result["vers"]){
                    version = result["vers"][ver];
                    verhtml +='<li><a href="javascript:;" onclick="verbkinfo(\''+version+'\',\''+service+'\')">'+version+'</a></li>';
                }
                versend = '</ul></div>';
                vershtml = vershead+verhtml+versend;
                $('#confinfo').html(vershtml);
            }else{

                $('#conflabel').text('无历史版本');
                $('#confquxiao').css('display','inline-block');
            }

        },
        complete: function(){

        },
        error: function(){

        }
   });
}



//配置变更页ip白名单框点击事件
function createipbox(){
     var obj_lis = document.getElementById("test").getElementsByTagName("li");
     for(var i=0;i<obj_lis.length;i++){
        obj_lis[i].onmouseover = function(){
            this.style.cursor = "default";
        };
        obj_lis[i].onclick = function(){
            if(this.value=="0"){
                this.style.backgroundColor="#ddd";
                this.value = "1";
            }else{
                this.style.backgroundColor="";
                this.value = "0";
            }

        }
    }
    var ipbox = document.getElementById("confips");
    ipbox.scrollTop = ipbox.scrollHeight;
}
function createiptext(){
    var tmpStr=[];
    for(var i=0;i<4;i++){
        v=i+1;
        tmpStr[i]="<input class=IPInput id=IPInput name=IP"+v+" type=text size=3 maxlength=3>"+(i==3?"":".");
    }
    document.getElementById("IPDiv").innerHTML=tmpStr.join("");
}
function addtestevent(){
    var aa=document.getElementById("IPDiv").getElementsByTagName("input");
    for (var i=0;i<aa.length;i++){
        aa[i].onkeyup = function (){
            this.value=this.value.replace(/[^\d]/g,'');
            key1=event.keyCode;
            if (key1==110) {
                this.blur();
                nextip=parseInt(this.name.substr(2,1));
                if(nextip==4){
                    document.getElementById("addip").focus();
                }else{
                    aa[nextip].focus();
                }
            }
            if(this.value.length>=3){
                if(parseInt(this.value)>=256) {
                    this.value="";
                    this.focus();
                    return  false;
                }else{
                    this.blur();
                    nextip=parseInt(this.name.substr(2,1));
                    if(nextip==4){
                    document.getElementById("addip").focus();
                    }else{
                    aa[nextip].focus();
                    }
                }
            }
        };
        aa[i].onbeforepaste=function(){
        clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''));
        };
    }
}
function ipadd(){
    var aa=document.getElementById("IPDiv").getElementsByTagName("input");
    var ip='';
    var flag = 0;
    for (var i=0;i<aa.length;i++){
        if(aa[i].value!=""){
            flag +=1;
        }
        if(i>=0 && i<3){
            ip += aa[i].value+'.';
        }else{
            ip += aa[i].value;
        }
        aa[i].value="";
    }
    var lis=document.getElementById("test").getElementsByTagName("li");
    for (var j=0;j<lis.length;j++){
        if(lis[j].innerHTML==ip){
            flag=0;
            alert("白名单中已存在该IP");
        }
    }
    if(flag==aa.length){
        var ipul = document.getElementById("test");
        ipul.innerHTML+='<li value="0">'+ip+'</li>';
        createipbox();
    }

}

function ipdel(){

    var aa=$("#test li[value='1']");
    aa.remove();
}


//操作记录
function execlog(name,service){
    $('#conftext').text(name+"相关操作记录");
    $('#loadingDiv').css('display','block');
    $('#popup').slideDown();
    var jdata = '{"service":"'+service+'"}';
    jdata = JSON.parse(jdata);
    $.get("/service/execlogs/",jdata, function(result){
        result = JSON.parse(result);
        var confhead='<table class="table table-striped table-bordered table-hover"><thead><tr><td>序号</td><td>客户</td><td>操作类型</td><td>操作详情</td><td>操作时间</td><td>操作人</td></tr></thead><tbody>';
        var confhtml='';
        for(var i=0;i<result.length;i++){
            var id= i+1;
            confhtml+='<tr><td>'+id+'</td>'+
                     '<td>'+result[i].lcustom+'</td>'+
                     '<td>'+result[i].cmd+'</td>'+
                     '<td>'+result[i].linfo+'</td>'+
                     '<td>'+result[i].ldate+'</td>'+
                     '<td>'+result[i].luser+'</td>'+
                 '</tr>';
        }
        var confend='</tbody></table>';
        confhtml = confhead+confhtml+confend;
        $('#conftable').html(confhtml);
        $('#confquxiao').html('关闭');
        $('#confquxiao').css('display','inline-block');
    });

}

function whoactive(){
    var uri = window.location.pathname;
    var urilist = uri.split("/");
    var cindex = $("#indextop");
    var cservice=$("#servicetop");
    var cversion=$("#versiontop");

    //index初始化
    cindex.addClass("");
    cindex.find("a").each(function () {
        $(this).addClass("");
    });
    //service初始化
    cservice.addClass("");
    cservice.find("a").each(function () {
        $(this).addClass("");
    });
    //version初始化
    cversion.addClass("");
    cversion.find("a").each(function () {
        $(this).addClass("");
    });
    //判断当前页面
    //首页
    if(urilist[1] ==""){
        $("#indexyb").addClass("active-menu");
    }else{
        $("#"+urilist[1]+"top").addClass("active");
        $("#"+urilist[1]+"top ul").addClass("nav nav-second-level collapse in");
        $("#"+urilist[1]+urilist[2]).addClass("active-menu");
    }

}